// 页面加载完成时检查并显示钱包地址
document.addEventListener('DOMContentLoaded', function () {
	const walletAddress = localStorage.getItem('walletAddress');

	if (walletAddress) {
		// 显示已存储的地址
		document.getElementById('walletAddress').textContent = walletAddress;
	} else {
		// 没有找到钱包地址时显示提示信息
		document.getElementById('walletAddress').textContent = '未找到钱包地址';
	}
});


// 初始化合约相关参数
const contractABI = [
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "spender",
				"type": "address"
			},
			{
				"internalType": "uint256",
				"name": "value",
				"type": "uint256"
			}
		],
		"name": "approve",
		"outputs": [
			{
				"internalType": "bool",
				"name": "",
				"type": "bool"
			}
		],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "address[]",
				"name": "recipients",
				"type": "address[]"
			},
			{
				"internalType": "uint256[]",
				"name": "amounts",
				"type": "uint256[]"
			}
		],
		"name": "batchTransferETH",
		"outputs": [],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "address[]",
				"name": "recipients",
				"type": "address[]"
			},
			{
				"internalType": "uint256[]",
				"name": "amounts",
				"type": "uint256[]"
			}
		],
		"name": "batchTransferTokens",
		"outputs": [],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "buyTokensWithETH",
		"outputs": [
			{
				"internalType": "bool",
				"name": "",
				"type": "bool"
			}
		],
		"stateMutability": "payable",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "_amount",
				"type": "uint256"
			}
		],
		"stateMutability": "nonpayable",
		"type": "constructor"
	},
	{
		"inputs": [],
		"name": "ECDSAInvalidSignature",
		"type": "error"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "length",
				"type": "uint256"
			}
		],
		"name": "ECDSAInvalidSignatureLength",
		"type": "error"
	},
	{
		"inputs": [
			{
				"internalType": "bytes32",
				"name": "s",
				"type": "bytes32"
			}
		],
		"name": "ECDSAInvalidSignatureS",
		"type": "error"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "spender",
				"type": "address"
			},
			{
				"internalType": "uint256",
				"name": "allowance",
				"type": "uint256"
			},
			{
				"internalType": "uint256",
				"name": "needed",
				"type": "uint256"
			}
		],
		"name": "ERC20InsufficientAllowance",
		"type": "error"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "sender",
				"type": "address"
			},
			{
				"internalType": "uint256",
				"name": "balance",
				"type": "uint256"
			},
			{
				"internalType": "uint256",
				"name": "needed",
				"type": "uint256"
			}
		],
		"name": "ERC20InsufficientBalance",
		"type": "error"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "approver",
				"type": "address"
			}
		],
		"name": "ERC20InvalidApprover",
		"type": "error"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "receiver",
				"type": "address"
			}
		],
		"name": "ERC20InvalidReceiver",
		"type": "error"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "sender",
				"type": "address"
			}
		],
		"name": "ERC20InvalidSender",
		"type": "error"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "spender",
				"type": "address"
			}
		],
		"name": "ERC20InvalidSpender",
		"type": "error"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "deadline",
				"type": "uint256"
			}
		],
		"name": "ERC2612ExpiredSignature",
		"type": "error"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "signer",
				"type": "address"
			},
			{
				"internalType": "address",
				"name": "owner",
				"type": "address"
			}
		],
		"name": "ERC2612InvalidSigner",
		"type": "error"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "account",
				"type": "address"
			},
			{
				"internalType": "uint256",
				"name": "currentNonce",
				"type": "uint256"
			}
		],
		"name": "InvalidAccountNonce",
		"type": "error"
	},
	{
		"inputs": [],
		"name": "InvalidShortString",
		"type": "error"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "owner",
				"type": "address"
			}
		],
		"name": "OwnableInvalidOwner",
		"type": "error"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "account",
				"type": "address"
			}
		],
		"name": "OwnableUnauthorizedAccount",
		"type": "error"
	},
	{
		"inputs": [
			{
				"internalType": "string",
				"name": "str",
				"type": "string"
			}
		],
		"name": "StringTooLong",
		"type": "error"
	},
	{
		"anonymous": false,
		"inputs": [
			{
				"indexed": true,
				"internalType": "address",
				"name": "owner",
				"type": "address"
			},
			{
				"indexed": true,
				"internalType": "address",
				"name": "spender",
				"type": "address"
			},
			{
				"indexed": false,
				"internalType": "uint256",
				"name": "value",
				"type": "uint256"
			}
		],
		"name": "Approval",
		"type": "event"
	},
	{
		"anonymous": false,
		"inputs": [],
		"name": "EIP712DomainChanged",
		"type": "event"
	},
	{
		"anonymous": false,
		"inputs": [
			{
				"indexed": true,
				"internalType": "address",
				"name": "from",
				"type": "address"
			},
			{
				"indexed": true,
				"internalType": "address",
				"name": "to",
				"type": "address"
			},
			{
				"indexed": false,
				"internalType": "uint256",
				"name": "amount",
				"type": "uint256"
			}
		],
		"name": "ETHTransferred",
		"type": "event"
	},
	{
		"anonymous": false,
		"inputs": [
			{
				"indexed": true,
				"internalType": "address",
				"name": "previousOwner",
				"type": "address"
			},
			{
				"indexed": true,
				"internalType": "address",
				"name": "newOwner",
				"type": "address"
			}
		],
		"name": "OwnershipTransferred",
		"type": "event"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "owner",
				"type": "address"
			},
			{
				"internalType": "address",
				"name": "spender",
				"type": "address"
			},
			{
				"internalType": "uint256",
				"name": "value",
				"type": "uint256"
			},
			{
				"internalType": "uint256",
				"name": "deadline",
				"type": "uint256"
			},
			{
				"internalType": "uint8",
				"name": "v",
				"type": "uint8"
			},
			{
				"internalType": "bytes32",
				"name": "r",
				"type": "bytes32"
			},
			{
				"internalType": "bytes32",
				"name": "s",
				"type": "bytes32"
			}
		],
		"name": "permit",
		"outputs": [],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "renounceOwnership",
		"outputs": [],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "tokenAmount",
				"type": "uint256"
			}
		],
		"name": "sellTokensForETH",
		"outputs": [
			{
				"internalType": "bool",
				"name": "",
				"type": "bool"
			}
		],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"anonymous": false,
		"inputs": [
			{
				"indexed": true,
				"internalType": "address",
				"name": "buyer",
				"type": "address"
			},
			{
				"indexed": false,
				"internalType": "uint256",
				"name": "amount",
				"type": "uint256"
			}
		],
		"name": "TokensPurchased",
		"type": "event"
	},
	{
		"anonymous": false,
		"inputs": [
			{
				"indexed": true,
				"internalType": "address",
				"name": "seller",
				"type": "address"
			},
			{
				"indexed": false,
				"internalType": "uint256",
				"name": "amount",
				"type": "uint256"
			}
		],
		"name": "TokensSold",
		"type": "event"
	},
	{
		"anonymous": false,
		"inputs": [
			{
				"indexed": true,
				"internalType": "address",
				"name": "from",
				"type": "address"
			},
			{
				"indexed": true,
				"internalType": "address",
				"name": "to",
				"type": "address"
			},
			{
				"indexed": false,
				"internalType": "uint256",
				"name": "amount",
				"type": "uint256"
			}
		],
		"name": "TokensTransferred",
		"type": "event"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "to",
				"type": "address"
			},
			{
				"internalType": "uint256",
				"name": "value",
				"type": "uint256"
			}
		],
		"name": "transfer",
		"outputs": [
			{
				"internalType": "bool",
				"name": "",
				"type": "bool"
			}
		],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"anonymous": false,
		"inputs": [
			{
				"indexed": true,
				"internalType": "address",
				"name": "from",
				"type": "address"
			},
			{
				"indexed": true,
				"internalType": "address",
				"name": "to",
				"type": "address"
			},
			{
				"indexed": false,
				"internalType": "uint256",
				"name": "value",
				"type": "uint256"
			}
		],
		"name": "Transfer",
		"type": "event"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "from",
				"type": "address"
			},
			{
				"internalType": "address",
				"name": "to",
				"type": "address"
			},
			{
				"internalType": "uint256",
				"name": "value",
				"type": "uint256"
			}
		],
		"name": "transferFrom",
		"outputs": [
			{
				"internalType": "bool",
				"name": "",
				"type": "bool"
			}
		],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "newOwner",
				"type": "address"
			}
		],
		"name": "transferOwnership",
		"outputs": [],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"stateMutability": "payable",
		"type": "fallback"
	},
	{
		"stateMutability": "payable",
		"type": "receive"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "owner",
				"type": "address"
			},
			{
				"internalType": "address",
				"name": "spender",
				"type": "address"
			}
		],
		"name": "allowance",
		"outputs": [
			{
				"internalType": "uint256",
				"name": "",
				"type": "uint256"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "account",
				"type": "address"
			}
		],
		"name": "balanceOf",
		"outputs": [
			{
				"internalType": "uint256",
				"name": "",
				"type": "uint256"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "decimals",
		"outputs": [
			{
				"internalType": "uint8",
				"name": "",
				"type": "uint8"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "DOMAIN_SEPARATOR",
		"outputs": [
			{
				"internalType": "bytes32",
				"name": "",
				"type": "bytes32"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "eip712Domain",
		"outputs": [
			{
				"internalType": "bytes1",
				"name": "fields",
				"type": "bytes1"
			},
			{
				"internalType": "string",
				"name": "name",
				"type": "string"
			},
			{
				"internalType": "string",
				"name": "version",
				"type": "string"
			},
			{
				"internalType": "uint256",
				"name": "chainId",
				"type": "uint256"
			},
			{
				"internalType": "address",
				"name": "verifyingContract",
				"type": "address"
			},
			{
				"internalType": "bytes32",
				"name": "salt",
				"type": "bytes32"
			},
			{
				"internalType": "uint256[]",
				"name": "extensions",
				"type": "uint256[]"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "ETH_USD_FEED_ADDRESS",
		"outputs": [
			{
				"internalType": "address",
				"name": "",
				"type": "address"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "account",
				"type": "address"
			}
		],
		"name": "getETHBalance",
		"outputs": [
			{
				"internalType": "uint256",
				"name": "",
				"type": "uint256"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "getETHUSDPrice",
		"outputs": [
			{
				"internalType": "int256",
				"name": "",
				"type": "int256"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "getTransactions",
		"outputs": [
			{
				"components": [
					{
						"internalType": "address",
						"name": "user",
						"type": "address"
					},
					{
						"internalType": "uint256",
						"name": "amountETH",
						"type": "uint256"
					},
					{
						"internalType": "uint256",
						"name": "amountECNY",
						"type": "uint256"
					},
					{
						"internalType": "bool",
						"name": "isPurchase",
						"type": "bool"
					}
				],
				"internalType": "struct eCNY.Transaction[]",
				"name": "",
				"type": "tuple[]"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "account",
				"type": "address"
			}
		],
		"name": "getTransactionsForAccount",
		"outputs": [
			{
				"components": [
					{
						"internalType": "address",
						"name": "user",
						"type": "address"
					},
					{
						"internalType": "uint256",
						"name": "amountETH",
						"type": "uint256"
					},
					{
						"internalType": "uint256",
						"name": "amountECNY",
						"type": "uint256"
					},
					{
						"internalType": "bool",
						"name": "isPurchase",
						"type": "bool"
					}
				],
				"internalType": "struct eCNY.Transaction[]",
				"name": "",
				"type": "tuple[]"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "name",
		"outputs": [
			{
				"internalType": "string",
				"name": "",
				"type": "string"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "owner",
				"type": "address"
			}
		],
		"name": "nonces",
		"outputs": [
			{
				"internalType": "uint256",
				"name": "",
				"type": "uint256"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "owner",
		"outputs": [
			{
				"internalType": "address",
				"name": "",
				"type": "address"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "symbol",
		"outputs": [
			{
				"internalType": "string",
				"name": "",
				"type": "string"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "totalSupply",
		"outputs": [
			{
				"internalType": "uint256",
				"name": "",
				"type": "uint256"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "",
				"type": "uint256"
			}
		],
		"name": "transactions",
		"outputs": [
			{
				"internalType": "address",
				"name": "user",
				"type": "address"
			},
			{
				"internalType": "uint256",
				"name": "amountETH",
				"type": "uint256"
			},
			{
				"internalType": "uint256",
				"name": "amountECNY",
				"type": "uint256"
			},
			{
				"internalType": "bool",
				"name": "isPurchase",
				"type": "bool"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "",
				"type": "address"
			},
			{
				"internalType": "uint256",
				"name": "",
				"type": "uint256"
			}
		],
		"name": "transactionsForAccount",
		"outputs": [
			{
				"internalType": "address",
				"name": "user",
				"type": "address"
			},
			{
				"internalType": "uint256",
				"name": "amountETH",
				"type": "uint256"
			},
			{
				"internalType": "uint256",
				"name": "amountECNY",
				"type": "uint256"
			},
			{
				"internalType": "bool",
				"name": "isPurchase",
				"type": "bool"
			}
		],
		"stateMutability": "view",
		"type": "function"
	}
]//合约ABI
const contractAddress = '0xB617D1AC68C184d193a79cd5C8FF55a69A4f08e6'; // 合约地址
const web3 = new Web3(window.ethereum); // 使用 MetaMask 注入的以太坊对象初始化 Web3
let contract; // 用于存储合约实例
let currentAccount; // 当前连接的以太坊账户
let transactionHistory = []; // 用于存储历史交易记录

// 页面加载完成后执行的初始化函数
document.addEventListener('DOMContentLoaded', async () => {
	// 请求连接以获取用户的以太坊账户
	await window.ethereum.request({ method: 'eth_requestAccounts' });
	currentAccount = (await web3.eth.getAccounts())[0]; // 获取当前账户地址
	contract = new web3.eth.Contract(contractABI, contractAddress); // 初始化合约对象

	// 绑定查看助记词按钮的点击事件
	document.getElementById('viewMnemonicButton').addEventListener('click', function () {
		fetch(`/generate-mnemonic?account=${currentAccount}`) // 发送请求生成助记词
			.then(response => response.json())
			.then(data => {
				document.getElementById('mnemonicDisplay').innerText = data.mnemonic; // 显示生成的助记词
			})
			.catch(error => console.error('Error:', error));
	});

	// 每隔 3 秒更新余额
	setInterval(updateBalance, 3000);
	updateTransactions(); // 初始加载交易记录
});

// 更新账户余额的函数
const updateBalance = async () => {
	try {
		const balance = await contract.methods.balanceOf(currentAccount).call(); // 获取当前账户余额
		document.getElementById('balanceDisplay').innerText = `余额: ${web3.utils.fromWei(balance, 'ether')} eCNY`; // 显示余额
	} catch (error) {
		console.error('获取余额失败:', error);
	}
};

// 获取并显示交易记录
const updateTransactions = async () => {
	try {
		const transactions = await contract.methods.getTransactionsForAccount(currentAccount).call();
		const transactionsDisplay = document.getElementById('transactionsDisplay');
		transactionsDisplay.innerHTML = ''; // 清空旧的交易记录

		// 显示每一笔交易
		transactions.forEach(transaction => {
			const amountEth = web3.utils.fromWei(transaction.amountETH.toString(), 'ether'); // 支出 ETH
			const amountECNY = web3.utils.fromWei(transaction.amountECNY.toString(), 'ether'); // 获得 eCNY

			const displayText = transaction.isPurchase
				? `购买 用户: ${transaction.user}，支出: ${amountEth} ETH，获得: ${amountECNY} eCNY`
				: `售出 用户: ${transaction.user}，卖出: ${amountECNY} eCNY，获得: ${amountEth} ETH`;

			const transactionElement = document.createElement('div');
			transactionElement.innerText = displayText;
			transactionsDisplay.appendChild(transactionElement); // 将交易信息显示在页面
		});
	} catch (error) {
		console.error("获取交易明细失败:", error);
	}
};

// 监听账户切换事件，更新当前账户地址
window.ethereum.on('accountsChanged', (accounts) => {
	currentAccount = accounts[0]; // 更新当前账户地址
	updateBalance(); // 更新余额
	updateTransactions(); // 更新交易记录
});

// 通用交易处理函数
const handleTransaction = async (method, args) => {
	try {
		const result = await contract.methods[method](...args).send({ from: currentAccount });
		console.log(`${method}成功:`, result);
		await updateTransactions(); // 更新交易记录
	} catch (error) {
		console.error(`${method}失败:`, error);
		alert(`${method}失败: ${error.message}`);
	}
};

// 购买代币按钮的点击事件
document.getElementById('buyButton').onclick = async () => {
	const amount = document.getElementById('buyAmount').value; // 获取输入的购买数量
	await handleTransaction('buyTokensWithETH', [], { value: web3.utils.toWei(amount, 'ether') });
};

// 出售代币按钮的点击事件
document.getElementById('sellButton').onclick = async () => {
	const amount = document.getElementById('sellAmount').value; // 获取输入的出售数量
	await handleTransaction('sellTokensForETH', [amount]);
};

// 批量转账按钮的点击事件
document.getElementById('batchTransferButton').onclick = async () => {
	const recipients = document.getElementById('recipients').value.split(','); // 获取多个接收者地址
	const amounts = document.getElementById('amounts').value.split(',').map(amount => web3.utils.toWei(amount, 'ether'));
	await handleTransaction('batchTransferTokens', [recipients, amounts]);
};

// 更新交易记录按钮点击事件
document.getElementById('checkTransactionsButton').onclick = updateTransactions;

// 查看助记词按钮的点击事件
document.getElementById('viewMnemonicButton').addEventListener('click', function () {
	fetch('/generate-mnemonic')
		.then(response => response.json())
		.then(data => {
			document.getElementById('mnemonicDisplay').innerText = data.mnemonic; // 显示助记词
		})
		.catch(error => console.error('Error:', error));
});

// 再次定义购买按钮点击事件以购买代币
document.getElementById('buyButton').onclick = async () => {
	const amount = document.getElementById('buyAmount').value;

	try {
		const result = await contract.methods.buyTokensWithETH().send({
			from: currentAccount,
			value: web3.utils.toWei(amount, 'ether')
		});
		console.log('购买成功:', result);
	} catch (error) {
		console.error('购买失败:', error);
	}
};

// 再次定义出售按钮点击事件以出售代币
document.getElementById('sellButton').onclick = async () => {
	const amount = document.getElementById('sellAmount').value;

	if (!amount || isNaN(amount) || amount <= 0) {
		alert('请输入有效的数量');
		return;
	}

	try {
		const result = await contract.methods.sellTokensForETH(web3.utils.toWei(amount, 'ether')).send({
			from: currentAccount
		});
		console.log('出售成功:', result);
	} catch (error) {
		console.error('出售失败:', error);
	}
};

// 再次定义批量转账按钮点击事件
document.getElementById('batchTransferButton').onclick = async () => {
	const recipients = document.getElementById('recipients').value.split(',');
	const amounts = document.getElementById('amounts').value.split(',').map(amount => web3.utils.toWei(amount, 'ether'));

	try {
		const result = await contract.methods.batchTransferTokens(recipients, amounts).send({
			from: currentAccount
		});
		console.log('批量转账成功:', result);
	} catch (error) {
		console.error('批量转账失败:', error);
	}
};

// 点击“检查交易”按钮，更新交易记录
document.getElementById('checkTransactionsButton').onclick = updateTransactions;
